Page({
  data: {
    rules: [
      {
        name: "type",
        rule: ["required"],
        msg: ["请选择发票类型"]
      },
      {
        name: "title",
        rule: ["required"],
        msg: ["请输入抬头"]
      },
      {
        name: "dutyParagraph",
        rule: ["required", "isNum"],
        msg: ["请输入税号", "税号仅为数字"]
      }
    ],
    isDefault: 1
  },
  onLoad: function (options) {
    let id = options.id;
    this.setData({
      id: id,
      delta: Number(options.delta)
    });
    if (id) {
      wx.setNavigationBarTitle({
        title: '更新发票信息',
      });
      wx.util.request('invoice.detail', {
        body: {id: id}
      }).then(res => {
        this.setData({
          type: res.type,
          title: res.title,
          dutyParagraph: res.duty_paragraph,
          isDefault: res.is_default
        });
      });
    }
  },
  invoiceType: function (e) {
    this.setData({
      type: e.detail.value,
    });
  },
  isDefault: function (e) {
    this.setData({
      isDefault: e.detail.value ? 1 : 0
    });
  },
  add: function (e) {
    let d = this.data,
        api = `invoice.${d.id ? 'modify' : 'new'}`,
        formData = e.detail.value;
    formData.type = d.type;
    if (d.type == 2) {
      d.rules.splice(2, 1);
    }
    let checkRes = wx.form.validation(formData, d.rules);
    if (checkRes) {
      wx.util.toast(checkRes);
    } else {
      wx.util.request(api, {
        query: `id=${d.id}`,
        body: {
          type: formData.type,
          title: formData.title,
          duty_paragraph: formData.dutyParagraph,
          is_default: d.isDefault
        }
      }).then(() => {
        wx.navigateBack({
          delta: d.delta
        });
      });
    }
  },
  del: function () {
    wx.util.request('invoice.del', {
      query: `id=${this.data.id}`
    }).then(() => {
      wx.navigateBack();
    });
  }
})